import { defineComponent, reactive, onMounted, ref, watch } from 'vue'
import { useStore } from 'vuex'
import { ElCard, ElTree, ElInput } from 'element-plus'
// import type { HomeTreeType } from './typings'
import tree1 from '~/assets/tree1.png'
import tree2 from '~/assets/tree2.png'
import tree3 from '~/assets/tree3.png'
import styles from './index.module.scss'

export default defineComponent({
  name: 'HomeTree',
  emits: ['handleNodeClick'],
  setup(props: any, { expose, emit }) {
    const store = useStore()
    const state = reactive({
      roleName: null,
      treeData: []
    })
    const elTreeRef = ref()
    //  tree数据
    const index = async () => {
      try {
        const { data } = await store.dispatch('runmap/HardwareTreeGet')
        state.treeData = data
      } catch (error) {}
    }
    //  tree节点点击
    const handleNodeClick = (row: any) => {
      emit('handleNodeClick', row)
    }
    //  筛选节点
    const filterNode = (value: string, data: any) => {
      if (!value) return true
      return data.title.indexOf(value) !== -1
    }
    //  tree图标
    const renderContent = (h: any, { node, data }: any) => {
      if (node.level === 1) {
        return (
          <div style="display: flex;align-items: center;">
            <img src={tree1} alt="" srcset="" />
            {data.title}
          </div>
        )
      } else if (node.level === 2) {
        return (
          <div style="display: flex;align-items: center;">
            <img src={tree2} alt="" srcset="" />
            {data.title}
          </div>
        )
      } else if (node.level === 3) {
        return (
          <div style="display: flex;align-items: center;">
            <img src={tree3} alt="" srcset="" />
            {data.title}
          </div>
        )
      }
    }
    watch(
      () => state.roleName,
      (newVal) => {
        elTreeRef.value.filter(newVal)
      }
    )
    onMounted(() => {
      index()
    })
    expose()
    return () => (
      <ElCard class={styles['home-tree']}>
        <div class="home-tree-label">回路监控箱列表</div>
        <div class="home-tree-input">
          <ElInput v-model={state.roleName} placeholder="关键字" />
        </div>
        <div class="home-tree-data">
          <ElTree
            ref={elTreeRef}
            data={state.treeData}
            props={{
              children: 'children',
              label: 'title'
            }}
            default-expand-all={true}
            onNode-click={handleNodeClick}
            filter-node-method={filterNode}
            render-content={renderContent}
          />
        </div>
      </ElCard>
    )
  }
})
